package com.lkd.job;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.lkd.common.VMSystem;
import com.lkd.dao.TaskDao;
import com.lkd.entity.TaskEntity;
import com.lkd.entity.UserCountEntity;
import com.lkd.feign.UserService;
import com.lkd.service.TaskService;
import com.lkd.vo.UserVO;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.LocalDate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Component
@Slf4j
public class UserJob {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private TaskDao taskDao;

    /**
     * 每日工单量列表初始化
     *
     * @param param
     * @return
     * @throws Exception
     */
    @XxlJob("workCountInitJobHandler")
    public ReturnT<String> workCountInitJobHandler(String param) {
        try {
            //获取每个人员未完成的工单数
            List<UserCountEntity> userIdTaskCount = taskDao.getUserIdTaskCount();
            //转换成map key是人员id value是工单数
            Map<Long, Long> collect = userIdTaskCount.stream()
                    .collect(Collectors.toMap(UserCountEntity::getUserId, UserCountEntity::getCount));

            List<UserVO> all = new ArrayList<>();
            List<UserVO> allOperators = userService.getAllOperators();
            List<UserVO> allRepairers = userService.getAllRepairers();
            all.addAll(allOperators);
            all.addAll(allRepairers);
            //工单初始化
            all.forEach(user -> {
                //使用redis的ZSet，key的规则，以固定字符串（前缀）VMSystem.REGION_TASK_KEY_PREF+日期+区域+人员角色（运营/运维）
                // 为key，以人员id做为值，以工单数作为分数(如果未完成工单中存在，就设置为未完成工单数，如果不存在，就设置为0)  过期时间为1天
                String key = VMSystem.generateUserTaskCount(user.getRoleCode(),user.getRegionId());
                long id = user.getUserId().longValue();
                redisTemplate.opsForZSet().add(key,user.getUserId()
                        ,collect.containsKey(id) ? collect.get(id) : 0);
                //1天之后过期
                redisTemplate.expire(key,Duration.ofDays(1));
        		
            });
            return ReturnT.SUCCESS;
        } catch (Exception e) {
            return ReturnT.FAIL;
        }
    }

    public static void main(String[] args) {
        String yyyyMMdd = LocalDate.now().toString("yyyyMMdd");
        System.out.println(yyyyMMdd);
    }

}